<!--
 * @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @Date: 2024-05-09 10:25:14
 * @LastEditors: icymoon911 icymoon911@163.com
 * @LastEditTime: 2024-08-08 18:34:04
 * @FilePath: \ken147258.topayClient\src\views\other\order-management\deal-list.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="app-container" v-loading="loading">
    <div class="search-container">
      <FormList :initForm="initSearchForm" v-model:formModel="searchForm"></FormList>
    </div>
    <el-card shadow="never" class="table-container">
      <template #header>
        <!-- <el-button type="primary" @click="handleQuery()"
          ><i-ep-refresh />刷新订单</el-button
        > -->
        <el-button type="success" @click="handleTableBtnClick({}, 'add')"
          ><i-ep-plus />新增</el-button
        >
        <!-- <el-text float-right line-height-32px class="mx-1 !mr-[20px]" type="info">更新倒计时：{{
          timeLog
        }}</el-text> -->
      </template>
      <comTable
        :data="tableDatasCom"
        :config="tableconfig"
        :tableHeader="tableHeader"
        @link-click="handleTableBtnClick"
      >
      </comTable>

      <pagination
        v-if="tableDatasObj.paging.total > 0"
        v-model:total="tableDatasObj.paging.total"
        v-model:page="tableDatasObj.paging.page"
        v-model:limit="tableDatasObj.paging.limit"
        @pagination="handleQuery"
      />
    </el-card>
    <!-- 弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      :width="dialog.width"
      append-to-body
      @close="dialog.closeDialog"
      @closed="dialog.closedDialog"
    >
      <FormList
        v-if="initDialogForm.initKeys.length"
        v-model:formRef="formDialogId"
        v-model:formModel="formDialogModel"
        :initForm="initDialogForm"
      ></FormList>
      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="dialog.leftBtnText"
            type="primary"
            @click="dialog.handleLeftClick"
            >{{ dialog.leftBtnText }}</el-button
          >
          <el-button v-if="dialog.rightBtnText" @click="dialog.handleRightClick">{{
            dialog.rightBtnText
          }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { watch, inject } from "vue";
import { FormInstance } from "element-plus";
import { list, add, dels, update as edit } from "@/api/text-config";
import { usePayProductStore } from "@/store";
import { cloneDeep } from "lodash";

const getFormatDate = inject("getFormatDate");
const getTimestamp = inject("getTimestamp");
const tableDatasObj = ref({
  list: [],
  paging: {
    limit: 20,
    page: 1,
    total: 0,
  },
  queryParams: {},
});
const loading = ref(false);

const options = {};

const searchForm = ref({});
const initSearchForm = ref({
  // 表单标签位置
  // labelPosition: "right",
  formAttrs: {
    // 是否内联
    inline: true,
  },
  rowAttrs: {
    // 行内表单数量
    columnsNum: 4,
  },
  // 初始化表单字段
  initKeys: [
    {
      // 类型
      type: "input",
      // 唯一标识
      key: "name",
      // 表单属性
      formAttrs: {
        label: "项名称",
      },
      // 控制属性
      controlAttrs: {
        // 是否可清空
        clearable: true,
      },
      // 控制事件
      controlOn: {},
    },
    {
      // 类型
      type: "input",
      // 唯一标识
      key: "des",
      // 表单属性
      formAttrs: {
        label: "说明",
      },
      // 控制属性
      controlAttrs: {
        // 是否可清空
        clearable: true,
      },
      // 控制事件
      controlOn: {},
    },
    {
      // 类型
      type: "input",
      // 唯一标识
      key: "code",
      // 表单属性
      formAttrs: {
        label: "代号",
      },
      // 控制属性
      controlAttrs: {
        // 是否可清空
        clearable: true,
      },
      // 控制事件
      controlOn: {},
    },
    {
      // 类型
      type: "input",
      // 唯一标识
      key: "content",
      // 表单属性
      formAttrs: {
        label: "内容",
      },
      // 控制属性
      controlAttrs: {
        // 是否可清空
        clearable: true,
      },
      // 控制事件
      controlOn: {},
    },
    {
      // 类型
      type: "buttons",
      // 按钮
      btns: [
        {
          // 文本
          text: "搜索",
          // 控制属性
          controlAttrs: {
            // 类型
            type: "primary",
            icon: "search",
          },
          // 控制事件
          controlOn: {
            // 点击
            click: (e: Event, formRef: FormInstance, data: object) => {
              formRef.validate((valid) => {
                if (valid) {
                  console.log("fields", data);
                  tableDatasObj.value.paging.page = 1;

                  let tempData = { ...data };

                  tableDatasObj.value.queryParams = tempData;

                  handleQuery(tableDatasObj.value.paging);
                }
              });
            },
          },
        },
        {
          // 文本
          text: "重置",
          // 控制属性
          controlAttrs: {
            icon: "refresh",
          },
          // 控制事件
          controlOn: {
            // 点击
            click: resetQuery,
          },
        },
      ],
    },
  ],
});

/** 重置查询 */
function resetQuery(e: Event, formRef: FormInstance, data: object) {
  // 重置表单
  formRef.resetFields();
  // formRef.resetFields();
  // 查询
  tableDatasObj.value.paging.page = 1;
  tableDatasObj.value.paging.limit = 20;
  tableDatasObj.value.queryParams = { ...searchForm.value };
  const params = {
    ...tableDatasObj.value.queryParams,
    ...data,
    ...tableDatasObj.value.paging,
  };

  handleQuery(params);
}

// 表*********************************************
const tableDatasCom = computed(() => {
  return tableDatasObj.value.list.map((item: ProductListVO) => {
    // const return_statusCom = options.return_status.find(
    //   (tItem) => tItem.value.toString() === item.return_status.toString()
    // )?.label;

    return {
      ...item,
      createtimeCom: getFormatDate(item.createtime),
      updatetimeCom: getFormatDate(item.updatetime),
    };
  });
});
const tableconfig = {
  // tableHeight: 480, //表格高度
  isSelection: false, //显示复选框
  isRowClick: false, //使用行点击
  isStripe: true, //隐藏斑马纹，与背景色不可同时用
  isShowSummary: false, //显示共计
  isIndex: true, //自定义序号
  isNeedPagination: true, //是否需要分页
};
const tableHeader = [
  { label: "ID", prop: "id", width: 200 },
  { label: "项名称", prop: "name", width: 200 },
  { label: "说明", prop: "des", minWidth: 200 },
  { label: "代号", prop: "code", width: 200 },
  { label: "内容", prop: "content", minWidth: 200 },
  { label: "创建时间", prop: "createtimeCom", width: 200 },
  { label: "更新时间", prop: "updatetimeCom", width: 200 },
  {
    label: "操作",
    isSort: false,
    prop: "operation",
    columnAttrs: {
      fixed: "right",
      width: "200",
    },
    children: [
      {
        type: "button",
        btnText: "修改",
        title: "edit",
      },
      {
        type: "button",
        btnText: "删除",
        title: "del",
      },
    ],
  },
];

/**
 * 查询
 */
function handleQuery(paging: { page: number; limit: number }) {
  loading.value = true;
  list({ ...tableDatasObj.value.paging, ...tableDatasObj.value.queryParams })
    .then((res) => {
      tableDatasObj.value.list = res.list;
      tableDatasObj.value.paging.total = res.total;

      // options.status = Object.keys(res.statusName).map((key) => ({
      //   label: res.statusName[key],
      //   value: key,
      // }));

      Object.keys(options).map((key) => {
        const item = initSearchForm.value.initKeys;
        const i = item.findIndex((item) => item.key === key);

        if (i > -1) {
          const control = initSearchForm.value.initKeys[i].controlAttrs;
          if (!(control.options && control.options.length)) {
            initSearchForm.value.initKeys[i].controlAttrs.options = options[key];
          }
        }
      });
    })
    .finally(() => {
      loading.value = false;
    });

  // loadstat();
  // if (tableDatasObj.paging.typeCode) {
  // loading.value = true;
  // getDictPage(queryParams)
  //   .then(({ data }) => {
  //     dictList.value = data.list;
  //     total.value = data.total;
  //   })
  //   .finally(() => (loading.value = false));
  // }
}

const initDialogForm = ref({
  // 表单标签位置
  formAttrs: {
    // 是否内联
    // inline: true,
    labelPosition: "top",
  },
  rowAttrs: {
    // 行内表单数量
    columnsNum: 1,
  },
  // 初始化表单字段
  initKeys: <any>[],
});

let initDialogFormBak = cloneDeep(initDialogForm.value);

const isHasOptions = [
  {
    // 标签
    label: "关闭",
    // 值
    value: 0,
  },
  {
    // 标签
    label: "开启",
    // 值
    value: 1,
  },
];

function handleTableBtnClick(row: object, title: string) {
  dialog.type = title;
  dialog.visible = true;
  dialog.singleData = tableDatasObj.value.list.find((item) => item.id === row.id);

  if (title === "add") {
    // 新增支付产品
    dialog.title = "新增";
    dialog.leftBtnText = "确 定";
    dialog.rightBtnText = "取 消";

    initDialogForm.value.initKeys = [
      {
        // 类型
        type: "input",
        // 唯一标识
        key: "name",
        // 表单属性
        formAttrs: {
          label: "项名称",
        },
        // 控制属性
        controlAttrs: {
          // 是否可清空
          clearable: true,
        },
        // 控制事件
        controlOn: {},
      },
      {
        // 类型
        type: "input",
        // 唯一标识
        key: "des",
        // 表单属性
        formAttrs: {
          label: "说明",
        },
        // 控制属性
        controlAttrs: {
          // 是否可清空
          clearable: true,
        },
        // 控制事件
        controlOn: {},
      },
      {
        // 类型
        type: "input",
        // 唯一标识
        key: "code",
        // 表单属性
        formAttrs: {
          label: "代号",
        },
        // 控制属性
        controlAttrs: {
          // 是否可清空
          clearable: true,
        },
        // 控制事件
        controlOn: {},
      },
      {
        // 类型
        type: "textarea",
        // 唯一标识
        key: "content",
        // 表单属性
        formAttrs: {
          label: "内容",
        },
        // 控制属性
        controlAttrs: {
          // 是否可清空
          clearable: true,
          rows: 5,
        },
        // 控制事件
        controlOn: {},
      },
    ];
  } else if (title === "edit") {
    dialog.visible = true;
    dialog.title = "编辑";
    dialog.leftBtnText = "确 定";
    dialog.rightBtnText = "取 消";
    // dialog.width = 400;

    // initDialogForm.value.rowAttrs.columnsNum = 1;

    // password 密码（6-18位）
    // mobile 手机号
    // email 邮箱
    // safety_code 安全码
    // status 状态(1:启用；2:禁用)

    initDialogForm.value.initKeys = [
      {
        // 类型
        type: "input",
        // 唯一标识
        key: "name",
        // 表单属性
        formAttrs: {
          label: "项名称",
        },
        // 控制属性
        controlAttrs: {
          // 是否可清空
          clearable: true,
        },
        // 控制事件
        controlOn: {},
      },
      {
        // 类型
        type: "input",
        // 唯一标识
        key: "des",
        // 表单属性
        formAttrs: {
          label: "说明",
        },
        // 控制属性
        controlAttrs: {
          // 是否可清空
          clearable: true,
        },
        // 控制事件
        controlOn: {},
      },
      {
        // 类型
        type: "input",
        // 唯一标识
        key: "code",
        // 表单属性
        formAttrs: {
          label: "代号",
        },
        // 控制属性
        controlAttrs: {
          // 是否可清空
          clearable: true,
        },
        // 控制事件
        controlOn: {},
      },
      {
        // 类型
        type: "textarea",
        // 唯一标识
        key: "content",
        // 表单属性
        formAttrs: {
          label: "内容",
        },
        // 控制属性
        controlAttrs: {
          // 是否可清空
          clearable: true,
          rows: 5,
        },
        // 控制事件
        controlOn: {},
      },
    ];

    const controls = initDialogForm.value.initKeys;

    controls
      .map((item) => item.key)
      .map((key, i) => {
        let val = dialog.singleData[key];
        initDialogForm.value.initKeys[i].value = val;
      });
  }
}

// 弹窗对象
const dialog = reactive({
  visible: false,
  type: "user-form",
  width: 450,
  title: "",
  leftBtnText: "确 定",
  rightBtnText: "取 消",
  singData: {},
  closeDialog() {
    dialog.visible = false;
    dialog.closedDialog();
  },
  closedDialog() {
    formDialogId.value = {};
    formDialogModel.value = {};
    initDialogForm.value.initKeys.splice(0);
    Object.keys(dialogBak).map((key) => {
      dialog[key] = dialogBak[key];
    });

    initDialogForm.value = cloneDeep(initDialogFormBak);
  },
  handleLeftClick() {
    if (dialog.type === "add") {
      formDialogId.value.validate((valid, fields) => {
        if (valid) {
          let params = { ...formDialogModel.value };

          add(params).then((res) => {
            ElMessage.success("添加成功");
            dialog.closeDialog();
            handleQuery();
          });
        }
      });
    } else if (dialog.type === "edit") {
      formDialogId.value.validate((valid, fields) => {
        if (valid) {
          let params = { ...formDialogModel.value, id: dialog.singleData.id };

          edit(params).then((res) => {
            ElMessage.success("修改成功");
            dialog.closeDialog();
            handleQuery();
          });
        }
      });
    }
  },
  handleRightClick() {
    dialog.closeDialog();
  },
});
const dialogBak = { ...dialog };

let formDialogId = ref<FormInstance>();

let formDialogModel = ref({});

onMounted(() => {
  tableDatasObj.value.queryParams = { ...searchForm.value };

  handleQuery(tableDatasObj.value.paging);

  // handleAutoRefreshChange(true);
});
</script>

<style lang="scss" scoped>
.info-container {
  font-size: var(--el-font-size-extra-small);

  span {
    background-color: #1e9fff;
    display: inline-block;
    padding: 0 10px;
    margin: 0 5px;
    color: #fff;
  }
}
</style>
